<template>
    <div class="process-list-wrapper">
        <a-tabs v-model:activeKey="activeKey" class="process-main" size="large" @change="handleChangeTabs">
            <a-tab-pane v-for="(item, index) in tabs" :key="index" :tab="item.title" />
        </a-tabs>
        <a-radio-group
            v-if="selectTab.type === 'todo'"
            class="tab-type-warp"
            :value="filterType"
            @change="handleChangeFilter"
        >
            <a-radio-button value="all">
                {{ t('all') }}
            </a-radio-button>
            <a-radio-button value="urged">
                {{ t('actions.urged') }}
            </a-radio-button>
        </a-radio-group>
        <div ref="tableWrapper" class="table-main-wrapper">
            <cart-table
                :columns="tabColumns"
                :type="selectTab.type"
                :data-source="pageData.data"
                :loading="pageData.loading"
                :pagination="pageData.pagination"
                @change="getTableList"
            >
                <template #action="{ record }">
                    <div class="detail-batch">
                        <a class="color-table-a" @click="handleShowDetail(record)">{{ t('processCenter.detail') }}</a>
                        <!-- 批量审批根据是否配置显示并且是我的待办 -->
                        <a
                            v-show="record.batchApprovalFlag && activeKey === 0"
                            class="color-table-a"
                            @click="handleBatchApproval"
                            >{{ t('processCenter.batchApproval') }}</a
                        >
                    </div>
                </template>
                <template #urged="{ record }">
                    <a-tag v-if="record.urged" class="urged-tag">
                        {{ t('actions.urged') }}
                    </a-tag>
                </template>
            </cart-table>
        </div>
    </div>
</template>

<script lang="ts">
    import { computed, reactive, ref } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { useI18n } from 'vue-i18n'
    import { cloneDeep } from 'lodash-es'
    import { $handleRedirect } from '@/utils/index'
    import { isNullOrEmpty } from '@/utils/is'
    import { getTodoList, getMyCreateList, getDoneList, getCcList } from '@/apis/sys/process'
    import CartTable from '../components/cartTable.vue'
    import { $getPublishedApplicationId } from '@/utils/common'
    // hooks-封装的tableMix
    import useTableBase from '@/hooks/useTable'
    const PUBLIC_PATH = import.meta.env.VITE_PUBLIC_PATH
    export default {
        name: 'Process',
        components: { CartTable },
        setup() {
            const router = useRouter()
            const route = useRoute()
            const { t } = useI18n()
            const activeKey = ref<number>(0)
            // const applicationId = $getPublishedApplicationId() || 0;
            const applicationId = $getPublishedApplicationId()
            const queryParams = reactive<PageListQuery<ProcessFilter, ProcessSort>>({
                filter: {
                    applicationId: applicationId
                },
                pageSize: 10,
                pageNo: 1,
                sort: {}
            })
            // 排序条件
            const sortInfo = reactive<ProcessSortInfo<ProcessSortInfoItem>>({
                todo: {
                    field: 'urgeTime',
                    direction: 'DESC'
                },
                done: {
                    field: 'endTime',
                    direction: 'DESC'
                },
                cc: {
                    field: 'endTime',
                    direction: 'DESC'
                }
            })
            const apiList = reactive<string[]>([getTodoList, getMyCreateList, getDoneList, getCcList])
            const pageData = reactive<ProcessPageData<ProcessPageDataItem>>({
                // 表单列
                columns: [],
                // 表单数据
                data: [],
                // 请求表单接口加载状态
                loading: false,
                // 请求列表是否出现错误
                error: false,
                // ant design  pagination,
                pagination: {
                    // table 总数
                    total: 0,
                    current: 1,
                    pageSize: 10,
                    pageNo: 1
                },
                // 请列表请求api
                fetchApi: null,
                // 表单选择的主键
                selectedRowKeys: [],
                // 克隆表单数据用于编辑
                cacheData: []
            })
            const tabs = reactive<
                {
                    title: string
                    type: ProcessStatus
                }[]
            >([
                {
                    title: t('myBoard.myToDo'),
                    type: 'todo'
                },
                {
                    title: t('myBoard.myProcess'),
                    type: 'my_create'
                },
                {
                    title: t('myBoard.myDeal'),
                    type: 'done'
                },
                {
                    title: t('myBoard.ccToMe'), // 暂时屏蔽掉抄送给我的tab
                    type: 'cc'
                }
            ])
            const filterType = ref<string>('all')
            // 重置请求数据
            const handleResetResponseData = resData => {
                const { content, totalElements } = resData
                const resultContent = ref<string[]>([])
                content.map(item => {
                    resultContent.value.push(item.approveInfo)
                })
                return {
                    content: resultContent,
                    totalElements
                }
            }
            const { handleResetQueryParams, fetchTablesData } = useTableBase(
                queryParams,
                pageData,
                handleResetResponseData
            )
            // 动态表单列
            const tabColumns = computed(() => {
                // 抄送列要插入哪个下标之前
                const list = reactive<
                    {
                        key: string
                        dataIndex?: string
                        title: string
                        scopedSlots?: {
                            customRender: string
                        }
                    }[]
                >([
                    {
                        key: 'taskId',
                        dataIndex: 'taskId',
                        title: t('processCenter.taskId')
                    },
                    {
                        key: 'applyUser',
                        dataIndex: 'applyUser',
                        title: t('processCenter.applyUser')
                    },
                    {
                        key: 'beginTime',
                        dataIndex: 'beginTime',
                        title: t('processCenter.beginTime')
                    },
                    {
                        key: 'action',
                        scopedSlots: { customRender: 'action' },
                        title: t('processCenter.action')
                    }
                ])
                return list
            })
            // 获取表格数据
            const getTableList = (pageNum = 1) => {
                pageData.pagination.current = pageNum
                pageData.fetchApi = apiList[activeKey.value]
                const queryParams = cloneDeep(handleResetQueryParams())
                // 如果是待办并且勾选了催办 则添加urged筛选条件
                if (selectTab.value.type === 'todo' && filterType.value === 'urged') {
                    queryParams.filter.urged = true
                }
                // 添加排序条件
                if (sortInfo[selectTab.value.type]) {
                    queryParams.sort = sortInfo[selectTab.value.type]
                }

                fetchTablesData(queryParams, () => {
                    pageData.loading = false // 接口调用成功后调用回调，关闭loading
                })
            }

            //  table切换后，更新表格数据
            const handleChangeTabs = () => {
                // 类型筛选重置为全部
                if (selectTab.value.type !== 'todo') {
                    filterType.value = 'all'
                }
                pageData.pagination.current = 1
                pageData.pagination.total = 0
                pageData.data = []
                pageData.loading = true // 增加loding状态
                getTableList()
            }
            const handleChangeFilter = event => {
                filterType.value = event.target.value
                handleChangeTabs()
            }
            // 去到批量审批页面
            const handleBatchApproval = () => {
                $handleRedirect(
                    `${PUBLIC_PATH}/process/batchApproval${
                        route.query.layoutPlanId ? '?layoutPlanId=' + route.query.layoutPlanId : ''
                    }`,
                    router
                )
            }
            const handleShowDetail = record => {
                $handleRedirect(
                    `${PUBLIC_PATH}/process/${record.processInstanceId}/${record.taskId}/${
                        tabs[activeKey.value].type
                    }?processStartId=${record.processStartId}${
                        route.query.layoutPlanId ? '&layoutPlanId=' + route.query.layoutPlanId : ''
                    }`,
                    router
                )
            }
            const selectTab = computed(() => {
                return tabs[activeKey.value]
            })
            const { type } = router.currentRoute.value.query
            activeKey.value = isNullOrEmpty(type) ? 0 : Number(type)
            getTableList()
            return {
                t,
                activeKey,
                pageData,
                tabs,
                filterType,
                selectTab,
                tabColumns,
                handleChangeFilter,
                getTableList,
                handleChangeTabs,
                handleBatchApproval,
                handleShowDetail,
                queryParams
            }
        }
    }
</script>

<style lang="less" scoped>
    .process-list-wrapper {
        height: 100%;
        width: 80%;
        margin: 0 auto;
        padding-top: 20px;

        :deep(.process-main > .@{ant-prefix}-tabs-bar) {
            text-align: center;
        }

        .table-main-wrapper {
            height: calc(100% - 106px);
            position: relative;
            padding: 0 16px;

            & > div {
                height: calc(100% - 40px);
                overflow: auto;

                :deep(ul) {
                    position: absolute;
                    bottom: 0;
                    right: 16px;
                }
            }

            .color-table-a {
                margin-right: 10px;
            }
        }
    }

    .tab-type-warp {
        margin-bottom: 16px;
        padding: 0 16px;
    }

    .urged-tag {
        background: rgba(244, 103, 75, 0.2);
        border-radius: 4px;
        color: #f4674b;
    }

    :deep(.@{ant-prefix}-radio-button-wrapper) {
        padding: 0 22px;
        color: #0070cc;

        &:first-child {
            border-radius: 4px 0 0 4px;
        }

        &:last-child {
            border-radius: 0 4px 4px 0;
        }
    }

    :deep(.@{ant-prefix}-tabs-bar) {
        border: none;
    }

    :deep(.@{ant-prefix}-tabs-nav) {
        justify-content: center;

        &::before {
            border: none;
        }

        & > div:first-child {
            border: 1px solid #3875ff;
            box-shadow: 0 4px 20px 0 #e5e9f6;
            border-radius: 8px;
            margin-bottom: 2px;
            color: #3875ff;
            flex: none;
        }

        .@{ant-prefix}-tabs-tab-active {
            background: #3875ff;
            border-radius: 8px;
            border: none;

            .@{ant-prefix}-tabs-tab-btn {
                color: #fff;
            }
        }
    }

    :deep(.@{ant-prefix}-tabs-ink-bar) {
        height: 0;
        background: none;
    }

    :deep(.@{ant-prefix}-tabs-nav .@{ant-prefix}-tabs-tab) {
        height: 40px;
        padding: 8px 22px;
    }
</style>

<i18n lang="yaml">
zh-CN:
    all: 全部
    actions:
        urged: 催办
    myBoard:
        myProcess: 我发起的
        ccToMe: 抄送我的
        myDeal: 我处理的
        myToDo: 我的待办
    processCenter:
        taskId: 流程编号
        applyUser: 发起人
        beginTime: 发起时间
        action: 操作
        detail: 详细
        batchApproval: 批量审批
en-US:
    all: whole
    actions:
        urged: Urge
    myBoard:
        myProcess: I initiated it
        ccToMe: Copy to me
        myDeal: I handled it
        myToDo: My to-do list
    processCenter:
        taskId: Process number
        applyUser: Initiator
        beginTime: Initiation time
        action: operation
        detail: detailed
        batchApproval: Batch approval
</i18n>
